/*
 *     This file is part of Mobile GPS Logger.
 *
 *     Mobile GPS Logger is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Mobile GPS Logger is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License v3 for more details.
 *
 *     You should have received a copy of the GNU General Public License v3
 *     along with Mobile GPS Logger. If not, see <http://www.gnu.org/licenses/>.
 */

package cx.ath.skyflyer.gpslog.ui;

import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

/**
 * To be used when a lengthy operation is to be performed.
 * @author Ahti Legonkov
 */
public class BusyIndicator extends Canvas {

    public BusyIndicator() {
        setFullScreenMode(true);
    }
    
    /**
     * Starts the animation timer.
     */
    public void beginAnimation() {
        timer.schedule(new TimerTask() {
            public void run() {
                BusyIndicator bi = BusyIndicator.this;
                ++bi.x;
                if (bi.isShown())
                    bi.repaint();
            }
        }, 100, 100);
    }

    protected void paint(Graphics g) {

        // XXX: is this a good place to cancel the timer?
        if (!isShown()) {
            timer.cancel();
            return;
        }
        
        final int width = getWidth();
        final int height = getHeight();

        g.setColor(255, 255, 255);
        g.fillRect(0, 0, width, height);

        for (int i = 0, c = 5; i < 10; ++i, c += 50) {
            if (c <= 255)
                g.setColor(255, 255-c, 255-c);
            else
                g.setColor(255, 255, 255);
            
            final int xx = ((x+i) % 10) * (width/10);
            final int yy = height/2;
            g.fillRect(xx, yy, 5, 5);
        }
    }

    private int x = 0;
    private Timer timer = new Timer();
}
